package com.elontian.http.sync.impl;

import java.io.DataOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpStatus;
import org.apache.http.conn.ConnectTimeoutException;

import com.elontian.http.sync.ISyncHttpRequest;
import com.elontian.util.IOUtil;

public class SyncHttpRequest implements ISyncHttpRequest {
	private int con_out_time = 15 * 1000;
	private int read_out_time = 15 * 1000;

	@Override
	public String get(String req) throws SocketTimeoutException,
			ConnectTimeoutException, NullPointerException, Exception {
		// TODO Auto-generated method stub

		// TODO Auto-generated method stub
		// Get方式请求
		// 新建一个URL对象
		String result = null;
		HttpURLConnection urlConn = null;
		try {
			URL url = new URL(req.trim());
			// 打开一个HttpURLConnection连接
			urlConn = (HttpURLConnection) url.openConnection();
			// 设置连接超时时间\
			urlConn.setConnectTimeout(con_out_time);
			urlConn.setReadTimeout(read_out_time);
			// 开始连接
			urlConn.connect();
			// 判断请求是否成功
			if (urlConn.getResponseCode() == HttpStatus.SC_OK) {
				// 获取返回的数据
				byte[] data = IOUtil.readStream(urlConn.getInputStream());
				result = new String(data);
			}

			if (result != null && !"".equals(result)) {
				// handler.sendFailMessage(new NullPointerException());
				// throw new NullPointerException();
				return result;
			} else {
				throw new NullPointerException();
			}

			// 关闭连接

			// 请求超时
		} catch (SocketTimeoutException e) {
			// TODO: handle exception
			// 处理超时 covers:
			// ClientProtocolException
			// ConnectTimeoutException
			// ConnectionPoolTimeoutException
			// SocketTimeoutException
			// throw e;
			// 连接超时
			// handler.fail(e);
			// handler.sendFailMessage(e);
			throw e;
		} catch (ConnectTimeoutException e) {
			// TODO: handle exception
			// handler.sendFailMessage(e);
			throw e;
		} catch (NullPointerException e) {
			// TODO: handle exception
			// handler.sendFailMessage(e);
			throw e;
		} catch (Exception e) {
			// TODO: handle exception
			// result = "请求异常";
			// handler.sendFailMessage(e);
			throw e;
		} finally {
			if (urlConn != null) {
				urlConn.disconnect();
			}
		}

	}

	@Override
	public String post(String req, Map<String, Object> params)
			throws SocketTimeoutException, ConnectTimeoutException,
			NullPointerException, Exception {
		// TODO Auto-generated method stub

		String result = null;
		HttpURLConnection urlConn = null;
		try {
			// String params = "id=" + URLEncoder.encode("helloworld", "UTF-8")
			// + "&pwd=" + URLEncoder.encode("android", "UTF-8");
			byte[] postData = this.mapToByte(params);
			URL url = new URL(req);
			urlConn = (HttpURLConnection) url.openConnection();
			urlConn.setConnectTimeout(con_out_time);
			urlConn.setReadTimeout(read_out_time);
			urlConn.setDoOutput(true);
			urlConn.setUseCaches(false);
			urlConn.setRequestMethod("POST");
			urlConn.setInstanceFollowRedirects(true);
			urlConn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencode");
			urlConn.connect();
			DataOutputStream dos = new DataOutputStream(
					urlConn.getOutputStream());
			dos.write(postData);
			dos.flush();
			dos.close();
			if (urlConn.getResponseCode() == HttpStatus.SC_OK) {
				byte[] data = IOUtil.readStream(urlConn.getInputStream());
				result = new String(data);
			}

			if (result != null && !"".equals(result)) {
				// handler.sendFailMessage(new NullPointerException());
				// throw new NullPointerException();
				return result;
			} else {
				throw new NullPointerException();
			}

		} catch (SocketTimeoutException e) {
			// TODO: handle exception
			// 处理超时 covers:
			// ClientProtocolException
			// ConnectTimeoutException
			// ConnectionPoolTimeoutException
			// SocketTimeoutException
			// throw e;
			// 连接超时
			// handler.fail(e);
			// handler.sendFailMessage(e);
			throw e;
		} catch (ConnectTimeoutException e) {
			// TODO: handle exception
			// handler.sendFailMessage(e);
			throw e;
		} catch (NullPointerException e) {
			// TODO: handle exception
			// handler.sendFailMessage(e);
			throw e;
		} catch (Exception e) {
			// TODO: handle exception
			// result = "请求异常";
			// handler.sendFailMessage(e);
			throw e;
		} finally {
			if (urlConn != null) {
				urlConn.disconnect();
			}
		}
	}

	private byte[] mapToByte(Map<String, Object> map)
			throws UnsupportedEncodingException {
		// TODO Auto-generated method stub

		StringBuffer buffer = new StringBuffer();
		Set<Map.Entry<String, Object>> set = map.entrySet();
		for (Iterator<Map.Entry<String, Object>> it = set.iterator(); it
				.hasNext();) {
			Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it
					.next();

			buffer.append(entry.getKey() + "="
					+ URLEncoder.encode(entry.getValue().toString(), "UTF-8"));

		}

		return buffer.toString().getBytes();

	}

}
